package com.ocom.payconfig.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.constant.PayConfigUrl;
import com.ocom.common.constant.WxServiceUrl;
import com.ocom.common.entity.card.EntityXfVideocallGroup;
import com.ocom.common.entity.card.EntityXfVideocallInfo;
import com.ocom.common.entity.master.EntityWechatAppInfo;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.videocall.request.*;
import com.ocom.common.request.xcx.XcxUserInfoVo;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.utils.wx.WxGhUtils;
import com.ocom.payconfig.service.WechatAppInfoService;
import com.ocom.payconfig.service.XfVideocallGroupService;
import com.ocom.payconfig.service.XfVideocallInfoService;
import com.ocom.payconfig.service.XfVideocallNoService;
import com.ocom.redis.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
public class VideoCallController {

    @Autowired
    private XfVideocallGroupService xfVideocallGroupService;

    @Autowired
    private XfVideocallNoService xfVideocallNoService;

    @Autowired
    private XfVideocallInfoService xfVideocallInfoService;

    @Resource
    private RedisUtil redisUtil;

    @Autowired
    private WechatAppInfoService wechatAppInfoService;


    @PostMapping(PayConfigUrl.URL_selectVideocallGroup)
    public Result selectVideocallGroup(@RequestBody SelectVideocallGroupRequest request) {
        return ResultUtil.success(xfVideocallGroupService.getVideocallGroupByPer(request.getComId(), request));
    }

    @PostMapping(PayConfigUrl.URL_saveAccredit)
    public Result saveAccredit(@RequestBody SaveAccreditRequest request) {
        return ResultUtil.success(xfVideocallNoService.saveAccreditInfo(request.getComId(), request));
    }


    @PostMapping(PayConfigUrl.URL_getVideocallOnShow)
    public Result getVideocallOnShow(@RequestBody DeviceManageOnShowRequest request) {
        List<EntityXfVideocallGroup> videocallGroup = xfVideocallGroupService.getVideocallGroup(request.getComId(), request.getMerchId());
        List<EntityXfVideocallInfo> videocallList = xfVideocallInfoService.getVideocallList(request.getComId(), request);
        Map<Long, List<EntityXfVideocallInfo>> infoMap = videocallList.stream().collect(Collectors.groupingBy(EntityXfVideocallInfo::getGroupId));
        List<EntityXfVideocallGroup> collect = videocallGroup.stream().map(e -> e.setInfoList(infoMap.get(e.getId()))).collect(Collectors.toList());
        return ResultUtil.success(collect);
    }

    @PostMapping(PayConfigUrl.URL_addVideocallGroup)
    public Result addVideocallGroup(@RequestBody EntityXfVideocallGroup request) {
        String token = getToken(0l, -200l, "xcx");
        String iotGroupId = WxGhUtils.createIotGroupId(token, request.getModelId(), request.getGroupName());
        if (null != iotGroupId) {
            request.setGroupId(iotGroupId);
            xfVideocallGroupService.addVideocallGroup(request.getComId(), request);
        } else {
            return ResultUtil.error(ResultEnum.Err_4118);
        }
        return ResultUtil.success();
    }

    @PostMapping(PayConfigUrl.URL_addVideocall)
    public Result addVideocall(@RequestBody DeviceManageAddDeviceRequest request) {
        //1.调微信注册设备
        EntityWechatAppInfo mach = wechatAppInfoService.getInfo(0l, -200l, "mach");
        JSONObject jsonObject = JSON.parseObject(mach.getAlipayPublicKey());

        String machToken = getToken(0l, -200l, "mach");

        List<String> deviceIds = new ArrayList<>();
        deviceIds.add(request.getSn());
        String s = WxGhUtils.addDevice(machToken, jsonObject.getInteger("productId"), jsonObject.getString("modelName"), deviceIds);
        if (null == s) {
            return ResultUtil.error(ResultEnum.Err_2016);
        }

        EntityXfVideocallGroup videocallGroup = xfVideocallGroupService.getById(request.getComId(), request.getGroupId());

        if (null != videocallGroup) {
            String xcxToken = getToken(request.getComId(), 0l, "xcx");

            String s1 = WxGhUtils.addIotGroupDevice(xcxToken, videocallGroup.getModelId(), videocallGroup.getGroupId(), request.getSn());

            JSONObject jsonObject1 = JSON.parseObject(s1);
            Integer errcode = jsonObject1.getInteger("errcode");
            if (errcode == 0) {
                JSONArray deviceList = jsonObject1.getJSONArray("device_list");
                JSONObject jsonObject2 = JSON.parseObject(JSON.toJSONString(deviceList.get(0)));
                if (jsonObject2.getInteger("errcode") == 0) {

                    EntityXfVideocallInfo entityXfVideocallInfo = new EntityXfVideocallInfo();
                    entityXfVideocallInfo.setComId(request.getComId());
                    entityXfVideocallInfo.setGroupId(videocallGroup.getId());
                    entityXfVideocallInfo.setGroupName(videocallGroup.getGroupName());
                    entityXfVideocallInfo.setModelId(videocallGroup.getModelId());
                    entityXfVideocallInfo.setSn(request.getSn());
                    entityXfVideocallInfo.setSnName(request.getSnName());
                    entityXfVideocallInfo.setRemark(request.getRemark());

                    return ResultUtil.success(xfVideocallInfoService.addVideocall(request.getComId(), entityXfVideocallInfo));
                }
                return ResultUtil.error(ResultEnum.Err_2016);
            } else {
                log.error("公话设备添加失败，【{}】",s1);
                ResultEnum resultEnum = ResultEnum.Err_2016;
                if (9800014 == errcode) {
                    resultEnum = ResultEnum.Err_4500;
                } else if (9800015 == errcode) {
                    resultEnum = ResultEnum.Err_4501;
                } else if (9800016 == errcode) {
                    resultEnum = ResultEnum.Err_4502;
                } else if (9800018 == errcode) {
                    resultEnum = ResultEnum.Err_4503;
                }
                return ResultUtil.error(resultEnum);
            }
        } else {
            return ResultUtil.error(ResultEnum.Err_2016);
        }
    }

    @PostMapping(PayConfigUrl.URL_updateVideocall)
    public Result updateVideocall(@RequestBody DeviceManageUpdateDeviceRequest request) {
        return ResultUtil.success(xfVideocallInfoService.updateVideocall(request.getComId(), request));
    }

    @PostMapping(PayConfigUrl.URL_actVideocall)
    public Result actVideocall(@RequestBody DeviceManageActDeviceRequest request) {
        Integer activeNumber = request.getActiveNumber();
        try {
            String token = getToken(0l, -200l, "xcx");

//            log.info("获取到token 【{}】",token);
            List<JSONObject> deviceIdList = new ArrayList<>();

            for (DeviceManageActDeviceRequest.ActDevice actDevice : request.getDeviceList()) {
                activeNumber++;

                JSONObject jsonObject31 = new JSONObject();
                jsonObject31.put("model_id", actDevice.getModelId());
                jsonObject31.put("sn", actDevice.getSn());
                jsonObject31.put("active_number", activeNumber);
                deviceIdList.add(jsonObject31);
            }

            //激活设备license
            String activeDevice = WxGhUtils.activeDevice(token, request.getPkgType(), deviceIdList);//资源包类型，0：测试体验包（默认），1：A 类设备，2：B 类设备，3：C 类设备，4：D 类设备，5：E类设备
            log.info("激活返回 【{}】【{}】【{}】【{}】",token,request,deviceIdList,activeDevice);
            JSONObject jsonObject1 = JSON.parseObject(activeDevice);
            if (jsonObject1.getInteger("errcode") == 0) {
                JSONArray deviceList = jsonObject1.getJSONArray("device_list");
                for (Object o : deviceList) {
                    JSONObject jsonObject2 = JSON.parseObject(JSON.toJSONString(o));
                    if (jsonObject2.getInteger("errcode") == 0) {
                        Date expireTime = new Date(jsonObject2.getLong("expire_time") * 1000l);
                        xfVideocallInfoService.updateExpireTime(request.getComId(), jsonObject2.getString("sn"), expireTime);
                    }
                }
            } else {
                return ResultUtil.error(ResultEnum.Err_2016);
            }
        } catch (Exception e) {
            log.info("激活异常 【{}】",e);
        }
        xfVideocallGroupService.updateActiveNumber(request.getComId(), request.getGroupId(), activeNumber);
        return ResultUtil.success();
    }

    @PostMapping(PayConfigUrl.URL_removeVideocall)
    public Result removeVideocall(@RequestBody DeviceManageRemoveDeviceRequest request) {

        for (DeviceManageRemoveDeviceRequest.RemoveDevice removeDevice : request.getDeviceList()) {
            //1.调微信删除设备组设备 TODO

            xfVideocallInfoService.removeVideocall(request.getComId(), removeDevice.getSn());//标记设备禁用即可
        }
        return ResultUtil.success();
    }

    @PostMapping(PayConfigUrl.URL_getNewVideocallList)
    public Result getNewVideocallList(@RequestBody DeviceManageOnShowDeviceRequest request) {

        return ResultUtil.success(xfVideocallInfoService.getNewVideocallList(request.getComId(), request.getMerchId()));
    }

    @PostMapping(PayConfigUrl.URL_getVideocallAppInfo)
    public Result getVideocallAppInfo(@RequestBody DeviceManageOnShowAppInfoRequest request) {

        EntityWechatAppInfo entityWechatAppInfo = wechatAppInfoService.getInfo(0l, -200l, "xcx");

        return ResultUtil.success(entityWechatAppInfo);
    }

    private String getToken(Long comId, Long merchId, String appName) {

        EntityWechatAppInfo entityWechatAppInfo = wechatAppInfoService.getInfo(comId, merchId, appName);

        Object tokenRedis = null;
        if (entityWechatAppInfo != null) {
            String canKey = "xcxToken:" + comId + ":" + entityWechatAppInfo.getAppid();
            tokenRedis = redisUtil.get(canKey);
            if (tokenRedis == null) {
                tokenRedis = WxGhUtils.getAccessToken(entityWechatAppInfo.getAppid(), entityWechatAppInfo.getAppsecret());
                if (tokenRedis != null) {
                    redisUtil.set(canKey, tokenRedis, 7000l);
                }
            }
        }
        return (String) tokenRedis;
    }
}
